﻿using AntDesign;
using CatTalkWeb_Blazor_Ver_.Shared;
using CatTalkWeb_Blazor_Ver_.Shared.Models;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace CatTalkWeb_Blazor_Ver_.Client {
    public static class GobalManager {
        static HttpClient _httpClient = new HttpClient();
        public static int nowPageIndex = 1, countPassages = 0;
        public delegate void OnStatementChanged();
        public static OnStatementChanged? dCusNVCD,dCatTalkBody;
        public static UsrInfo? myUsrInfo;
        //后端服务器配置地址
        public static string serverURL = @"http://localhost:8080/Api/CatTalkServer";

        //全局初始化函数
        public static void Init() {
            //放到AppRazor中写了

        }
        /// <summary>
        /// 获取数据库中所有的文章（每次5条）
        /// </summary>
        /// <returns></returns>
        //public async static Passage[] getPassageList() {
        //    await 
        //    return new Passage[] { };
        //}

        public async static Task<Passage?> getPassageById(int id){
            Passage? getPassage;
            try {
                 getPassage = await _httpClient.GetFromJsonAsync<Passage?>(GobalManager.serverURL + @"/GetPassageByID?id=" + id.ToString());
                if (getPassage != null && getPassage.Id == 0) {
                    getPassage = null;
                }
            }catch(Exception ex) {
                throw ex;
            }
            return getPassage;
        }

        public async static Task<UsrInfo?> GetUsrInfoById(int id) {
            var getUsrInfo = await _httpClient.GetFromJsonAsync<UsrInfo>(GobalManager.serverURL + "/GetUsrInfoByID?id=" + id);
            if (getUsrInfo != null && getUsrInfo.ID == 0) {
                getUsrInfo = null;
            }
            return getUsrInfo;
        }
        /// <summary>
        /// 获取5条数据
        /// </summary>
        /// <param name="inexPage">下标从1开始</param>
        /// <returns>数组</returns>
        public async static Task<Passage[]> GetPassages(int inexPage) {
            var resp = await _httpClient.GetFromJsonAsync<Passage[]>(GobalManager.serverURL + "/GetPassages?pageIndex=" + inexPage);
            if (resp != null) {
                return resp;
            } else {
                return new Passage[0];
            }
        }
    }
}
